package com.tjbaobao.happybirthday;

import android.Manifest;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import com.tjbaobao.framework.entity.ui.TitleBarInfo;
import com.tjbaobao.framework.ui.BaseTitleBar;
import com.tjbaobao.framework.util.BaseTimerTask;
import com.tjbaobao.framework.util.Tools;

import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppActivity implements EasyPermissions.PermissionCallbacks , BaseTitleBar.OnTitleBarClickListener{

    private static final int RE_READ_PERMISSIONS = 1;

    private VideoProgressBar progressBar ;
    private MediaPlayer mMediaPlayer ;

    private View rl_record;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    private void initView()
    {

    }

    @Override
    protected void onInitValues(Bundle savedInstanceState) {
        isOnclickTwoExit();
    }

    @Override
    protected void onInitView() {
        setContentView(R.layout.activity_main);
        immersiveStatusBar();
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {

        } else {
            EasyPermissions.requestPermissions(this, "自定义音乐需要文件读取权限",
                    RE_READ_PERMISSIONS, perms);
        }
        progressBar = this.findViewById(R.id.progressBar);
        progressBar.setProgressBGColor(getColorById(R.color.app_gray_left));
        rl_record = this.findViewById(R.id.rl_record);

    }

    @Override
    protected void onInitTitleBar(BaseTitleBar titleBar) {
        titleBar.setTitle("");
    }

    @Override
    protected void onLoadData() {

    }

    private boolean isPlay = false;
    private long startTime = 0;
    private boolean isCanPlay = true;
    private  Animation animation ;
    private boolean isAnimStart = false;
    private void play()
    {

        if(isPlay||!isCanPlay)
        {
            return ;
        }
        startTime = System.currentTimeMillis();
        isPlay = true;
        rl_record.setAnimation(animation);
        rl_record.startAnimation(animation);
        isAnimStart = true;
        mMediaPlayer.start();
    }

    private void stop()
    {
        if(!isPlay)
        {
            return ;
        }
        if(System.currentTimeMillis()-startTime<10000)
        {
            return ;
        }
        isPlay =false;
        if(mMediaPlayer.isPlaying())
        {
            mMediaPlayer.pause();
        }
        animation.cancel();
        isAnimStart = false;
    }

    private SensorManager mSensorManager ;
    private MySensorEventListener mSensorEventListener ;
    private BaseTimerTask mBaseTimerTask;
    @Override
    protected void onStart() {
        super.onStart();
        mMediaPlayer = MediaPlayer.create(context,R.raw.music);
        mMediaPlayer.setOnPreparedListener(new MyOnPreparedListener());
        animation = AnimationUtils.loadAnimation(context,R.anim.app_refresh_anim);
        isAnimStart = true;
        if(mSensorManager==null&& (Boolean) Tools.getSharedPreferencesValue("switch",false))
        {
            mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
            mSensorEventListener = new MySensorEventListener();
            mSensorManager.registerListener(mSensorEventListener,sensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
        if(mBaseTimerTask==null)
        {
            mBaseTimerTask = new BaseTimerTask(){
                @Override
                public void run() {
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(sensorValue>(int)Tools.getSharedPreferencesValue("value",8)&& (Boolean) Tools.getSharedPreferencesValue("switch",false))
                            {
                                play();
                            }
                            else
                            {
                                stop();
                            }
                            float progress = (float)mMediaPlayer.getCurrentPosition()/(float)duration;
                            progressBar.setProgress(progress);
                        }
                    });
                }
            };
        }
        mBaseTimerTask.startTimer(0,500);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isCanPlay = true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSensorManager.unregisterListener(mSensorEventListener);
        mMediaPlayer.stop();
    }
    private long duration = 0;
    private class MyOnPreparedListener implements MediaPlayer.OnPreparedListener
    {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            duration = mediaPlayer.getDuration();

        }
    }

    private float sensorValue =0;
    private class MySensorEventListener implements SensorEventListener
    {
        @Override
        public void onSensorChanged(SensorEvent sensorEvent) {
            float value = sensorEvent.values[0];
            sensorValue = value;

        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int i) {

        }
    }


    @Override
    public <V extends TitleBarInfo.BaseView> void onTitleBarClick(int i, int i1, V v) {
        if(i==BaseTitleBar.LAYOUT_RIGHT&&i1==0)
        {
            startActivity(SettingActivity.class);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        initView();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }
}
